#include <jni.h>
#include "StopMemory.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "extr_api.h"

/*
 * Class:     StopMemory
 * Method:    CreateStopMemory_helper
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_StopMemory_CreateStopMemory_1helper
  (JNIEnv *env, jobject obj)
{
	jclass cls = (*env)->GetObjectClass(env, obj);
	jfieldID fid;
	void  *StopMemory;
	int errorCode;

	fid = (*env)->GetFieldID(env, cls, "lng_stop_mem_ptr", "J");
	if (fid == 0)
	{
		return -1;
	}
	
	errorCode = ExtrCreateStopMemory(&StopMemory);
	if (errorCode != 0)
	{
		return errorCode;
	}

	(*env)->SetLongField(env, obj, fid, (long)StopMemory);

	return errorCode;
}

/*
 * Class:     StopMemory
 * Method:    ClearStopMemory_helper
 * Signature: (J)I
 */
JNIEXPORT jint JNICALL Java_StopMemory_ClearStopMemory_1helper
  (JNIEnv *env, jobject obj, jlong StopMem)
{
	return ExtrClearStopMemory((void *)StopMem);
}

/*
 * Class:     StopMemory
 * Method:    GetErrorMessage_helper
 * Signature: (I)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_StopMemory_GetErrorMessage_1helper
  (JNIEnv *env, jobject obj, jint ErrorCode)
{
	char *ErrorMessage;
	ExtrGetErrorMessage(ErrorCode, &ErrorMessage);
	return (*env)->NewStringUTF(env, ErrorMessage);
}

/*
 * Class:     StopMemory
 * Method:    AddStopWord_helper
 * Signature: (JII[B)I
 */
JNIEXPORT jint JNICALL Java_StopMemory_AddStopWord_1helper
  (JNIEnv *env, jobject obj, jlong StopMem, jint LanguageID, jint CharCodeID, jbyteArray word)
{
	jbyte *str_word = (*env)->GetByteArrayElements(env, word, 0);
	int int_return = ExtrAddStopWord((void *)StopMem, LanguageID, CharCodeID, (void *)str_word);
	(*env)->ReleaseByteArrayElements(env, word, str_word, 0);
	return int_return;
}

/*
 * Class:     StopMemory
 * Method:    AddStopPhrase_helper
 * Signature: (JIILjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_StopMemory_AddStopPhrase_1helper
  (JNIEnv *env, jobject obj, jlong StopMem, jint LanguageID, jint CharCodeID, jbyteArray phrase)
{
	jbyte *str_phrase = (*env)->GetByteArrayElements(env, phrase, 0);
	int int_return = ExtrAddStopPhrase((void *)StopMem, LanguageID, CharCodeID, (void *)str_phrase);
	(*env)->ReleaseByteArrayElements(env, phrase, str_phrase, 0);
	return int_return;
}
